package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;


import weixinpojo.ImagetMessage;
import weixinpojo.ItemOfNewsMessage;
import weixinpojo.Location;
import weixinpojo.NewsMessage;
import weixinpojo.TextMessage;

public class MessageUtil {
	
	
	
	
	
	//把微信传过来的xml转成map
	public static Map<String, String> xmlToMap(HttpServletRequest request)
			throws IOException, DocumentException {
		Map<String, String> map = new HashMap<>();
		SAXReader reader = new SAXReader();
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		Element root = doc.getRootElement();
		List<Element> elelist = root.elements();
		for (Element e : elelist) {
			map.put(e.getName(), e.getText());
		}
		ins.close();

		return map;
	
	 }
	
	
	
	
	/**微信文本对象转成xml字符串返回
	 * @param message
	 * @return
	 */
	public static String textMessageToXml(TextMessage message){
		XStream xStream = new XStream();
		xStream.alias("xml", message.getClass());
		return xStream.toXML(message);
		
	}
	
	/**微信图片对象转成xml字符串返回
	 * @param message
	 * @return
	 */
	public static String imageMessageToXml(ImagetMessage image){
		XStream xStream = new XStream();
		xStream.alias("xml", image.getClass());
		xStream.alias("image", image.getImage().getClass());
		return xStream.toXML(image);
		
	}

	/**
	 * 将地理位置转化为xml
	 * @param location
	 * @return
	 */
	
	public static String locationToXml(Location location){
		XStream xStream = new XStream();
		xStream.alias("xml", location.getClass());
		return xStream.toXML(location);
	}
	
	/**
	 * 将微信图文消息转化为xml
	 * @param newsMessage
	 * @return
	 */
	
	public static String newsMessageToXml(NewsMessage newsMessage ){
		XStream xStream = new XStream();
		xStream.alias("xml", newsMessage.getClass());
		xStream.alias("item", new ItemOfNewsMessage().getClass());
		return xStream.toXML(newsMessage);
	}	
		
		
}
